import Koa from 'koa'
import bodyparser from 'koa-bodyparser'
import logger from 'koa-logger'

const app = new Koa()

// middleware
import Cros from './lib/Cros'
import ErrorHandle from './lib/ErrorHandle'
import RouterRegister from './lib/RouterRegister'
import LoadUser from './lib/LoadUser'

// lib
import encrypt from './lib/Encrypt'

// model
import { db } from './model'

// mount model
Object.assign(app.context, { db, encrypt })
// middleware
app.use(bodyparser({
  enableTypes: ['json', 'form', 'text'],
}))
app.use(require('koa-static')(__dirname + '/public'))
app.use(Cros)
app.use(LoadUser)
app.use(logger())
app.use(ErrorHandle)
// router
RouterRegister(app)
// logger
app.use(async (ctx, next) => {
  const start = new Date()
  await next()
  const ms = new Date() - start
  console.log(`${ctx.method} ${ctx.url} - ${ms}ms`)
})

export default app
